<template>
  <div class="admin-profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>管理员信息</span>
          <el-button type="primary" @click="handleEdit">编辑资料</el-button>
        </div>
      </template>
      
      <div class="profile-content">
        <div class="avatar-section">
          <el-avatar :size="100" :src="adminInfo.avatar" />
          <h2>{{ adminInfo.username }}</h2>
          <el-tag type="danger">管理员</el-tag>
        </div>

        <el-descriptions :column="2" border class="admin-descriptions">
          <el-descriptions-item label="用户名">
            {{ adminInfo.username }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ adminInfo.email || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ adminInfo.phone || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">
            {{ adminInfo.registerTime || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item label="最后登录">
            {{ adminInfo.lastLoginTime || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item label="登录IP">
            {{ adminInfo.lastLoginIp || '未知' }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="admin-stats">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8">
              <el-card shadow="hover">
                <template #header>
                  <div class="stat-header">
                    <el-icon><User /></el-icon>
                    <span>用户总数</span>
                  </div>
                </template>
                <div class="stat-value">{{ stats.userCount }}</div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8">
              <el-card shadow="hover">
                <template #header>
                  <div class="stat-header">
                    <el-icon><DataLine /></el-icon>
                    <span>今日访问</span>
                  </div>
                </template>
                <div class="stat-value">{{ stats.todayVisits }}</div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>

    <!-- 编辑资料对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑资料"
      width="500px"
      :append-to-body="true"
    >
      <el-form
        ref="formRef"
        :model="editForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Reading, DataLine, Plus } from '@element-plus/icons-vue'

// 管理员信息
const adminInfo = ref({
  username: '',
  email: '',
  phone: '',
  avatar: '',
  registerTime: '',
  lastLoginTime: '',
  lastLoginIp: ''
})

// 统计数据
const stats = ref({
  userCount: 0,
  courseCount: 0,
  todayVisits: 0
})

// 编辑表单
const dialogVisible = ref(false)
const formRef = ref(null)
const editForm = ref({
  username: '',
  email: '',
  phone: '',
  avatar: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 获取管理员信息
const getAdminInfo = () => {
  // 模拟API调用，从localStorage获取用户名和头像，邮箱使用默认或从localStorage获取
  adminInfo.value = {
    username: localStorage.getItem('username') || 'admin',
    email: localStorage.getItem('email') || 'admin@example.com', // 假设管理员默认邮箱或从其他地方获取
    phone: localStorage.getItem('phone') || '未设置', // 假设手机号从localStorage获取
    avatar: localStorage.getItem('avatar') || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png', // 更改头像地址避免缓存
    registerTime: localStorage.getItem('registerTime') || '未知', // 假设从localStorage获取注册时间
    lastLoginTime: localStorage.getItem('lastLoginTime') || '未知', // 假设从localStorage获取最后登录时间
    lastLoginIp: localStorage.getItem('lastLoginIp') || '未知' // 假设从localStorage获取登录IP
  }
  // 为了匹配截图中的邮箱和用户名，这里可以先硬编码或者确保localStorage中有对应值
  // adminInfo.value.username = 'ptyh' // 如果需要精确匹配截图
  // adminInfo.value.email = '66555555555@qq.com' // 如果需要精确匹配截图
}

// 获取统计数据
const getStats = () => {
  // 模拟API调用，实际应从后端获取
  
  // 从 localStorage 获取用户总数
  const savedUserList = localStorage.getItem('userList');
  let userCount = 0;
  if (savedUserList) {
    try {
      const userList = JSON.parse(savedUserList);
      userCount = userList.length;
    } catch (e) {
      console.error('Failed to load user list from localStorage for stats:', e);
    }
  }

  // 从 localStorage 获取课程总数
  const savedCourseList = localStorage.getItem('courseList');
  let courseCount = 0;
  if (savedCourseList) {
    try {
      const courseList = JSON.parse(savedCourseList);
      courseCount = courseList.length;
    } catch (e) {
      console.error('Failed to load course list from localStorage for stats:', e);
    }
  }

  stats.value = {
    userCount: userCount,
    courseCount: courseCount,
    todayVisits: 789 // 今日访问仍然是模拟数据
  }
}

// 处理编辑按钮点击
const handleEdit = () => {
  // 将当前显示的信息复制到编辑表单，邮箱和手机号从adminInfo.value获取以保证能编辑当前显示的值
  editForm.value = {
    username: adminInfo.value.username,
    email: adminInfo.value.email === '未设置' ? '' : adminInfo.value.email, // 如果邮箱是"未设置"，编辑时显示为空
    phone: adminInfo.value.phone === '未设置' ? '' : adminInfo.value.phone, // 如果手机号是"未设置"，编辑时显示为空
    avatar: adminInfo.value.avatar
  }
  dialogVisible.value = true
}

// 处理头像上传成功
const handleAvatarSuccess = (response) => {
  // 假设response.url是上传成功后的头像URL
  if (response && response.url) {
    editForm.value.avatar = response.url
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败')
  }
}

// 处理保存
const handleSave = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      // 模拟API调用，实际应调用后端接口保存信息
      // 更新localStorage中的信息
      localStorage.setItem('username', editForm.value.username)
      localStorage.setItem('email', editForm.value.email)
      localStorage.setItem('phone', editForm.value.phone)
      localStorage.setItem('avatar', editForm.value.avatar)
      
      // 更新页面显示的信息
      adminInfo.value.username = editForm.value.username
      adminInfo.value.email = editForm.value.email
      adminInfo.value.phone = editForm.value.phone
      adminInfo.value.avatar = editForm.value.avatar
      
      ElMessage.success('资料保存成功')
      dialogVisible.value = false
    }
  })
}

onMounted(() => {
  getAdminInfo()
  getStats()
})
</script>

<style scoped>
.admin-profile {
  max-width: 1000px; /* 调整最大宽度 */
  margin: 20px auto; /* 居中并增加上下边距 */
  padding: 0 20px; /* 增加左右内边距 */
}

.profile-card {
  margin-bottom: 20px; /* 增加卡片下边距 */
  border-radius: 8px; /* 添加圆角 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 20px; /* 调整头部内边距 */
  border-bottom: 1px solid var(--el-card-border-color); /* 添加底部边框 */
  margin-bottom: 20px; /* 增加头部下边距 */
}

.card-header span {
    font-size: 20px; /* 调整标题字体大小 */
    font-weight: bold; /* 加粗标题 */
    color: var(--el-text-color-primary); /* 标题颜色 */
}

.profile-content {
  padding: 0 20px 20px; /* 调整内容内边距 */
}

.avatar-section {
  text-align: center;
  margin-bottom: 30px; /* 增加头像部分下边距 */
  padding-bottom: 20px; /* 添加底部内边距 */
  border-bottom: 1px solid var(--el-border-color-light); /* 添加底部边框 */
}

.avatar-section .el-avatar {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 添加头像阴影 */
}

.avatar-section h2 {
  margin: 15px 0 8px; /* 调整用户名上下边距 */
  font-size: 22px; /* 调整用户名字体大小 */
  color: var(--el-text-color-regular); /* 用户名颜色 */
}

.avatar-section .el-tag {
    font-size: 14px; /* 调整标签字体大小 */
    height: 24px; /* 调整标签高度 */
    line-height: 22px; /* 调整标签行高 */
}

.admin-descriptions {
  margin-top: 0; /* 移除顶部外边距 */
  margin-bottom: 30px; /* 增加下边距 */
}

/* 调整Descriptions的样式 */
:deep(.el-descriptions__title) {
    font-size: 18px;
    font-weight: bold;
    color: var(--el-text-color-primary);
}

:deep(.el-descriptions-item__label) {
    background-color: var(--el-fill-color-light); /* 标签背景色 */
    padding: 10px 15px; /* 调整标签内边距 */
    font-weight: bold;
    color: var(--el-text-color-regular); /* 标签字体颜色 */
}

:deep(.el-descriptions-item__content) {
    padding: 10px 15px; /* 调整内容内边距 */
    color: var(--el-text-color-primary); /* 内容字体颜色 */
}

.admin-stats {
  margin-top: 20px; /* 调整统计数据部分上边距 */
}

.admin-stats .el-card {
    border-radius: 8px; /* 添加圆角 */
}

.admin-stats .el-card__header {
    padding: 15px; /* 调整统计卡片头部内边距 */
    border-bottom: none; /* 移除底部边框 */
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px; /* 调整统计项标题字体大小 */
  color: var(--el-text-color-regular); /* 统计项标题颜色 */
}

.stat-header .el-icon {
    font-size: 20px;
    color: var(--el-color-primary); /* 图标颜色 */
}

.stat-value {
  font-size: 28px; /* 调整统计数值字体大小 */
  font-weight: bold;
  color: var(--el-color-primary); /* 统计数值颜色 */
  text-align: center;
  padding: 10px 0; /* 添加上下内边距 */
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: block;
  object-fit: cover; /* Ensures the image covers the area without distortion */
  border: 2px solid var(--el-color-primary-light-3); /* 添加边框 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}

.avatar-uploader .el-upload {
  border: 2px dashed var(--el-border-color); /* 调整边框样式 */
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  background-color: var(--el-fill-color-light); /* 添加背景色 */
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary); /* 鼠标悬停边框颜色 */
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

/* 调整Descriptions的样式 */
:deep(.el-descriptions) {
    margin-top: 20px;
}

:deep(.el-descriptions__title) {
    font-size: 18px;
    font-weight: bold;
}

:deep(.el-descriptions-item__label) {
    background-color: var(--el-fill-color-light);
    padding: 8px 12px;
    font-weight: bold;
}

:deep(.el-descriptions-item__content) {
    padding: 8px 12px;
}
</style> 